﻿using OfficeOpenXml;
using OfficeOpenXml.Style;
using System;
using System.Reflection;
using System.Collections.Generic;
using System.Drawing;
using System.IO;

namespace NewChillers.Helpers
{
    /// <summary>
    /// Excel导出帮助类
    /// </summary>
    public static class ExcelExportHelper
    {
        /// <summary>
        /// 导出数据到Excel文件
        /// </summary>
        /// <typeparam name="T">数据类型</typeparam>
        /// <param name="data">要导出的数据列表</param>
        /// <param name="columnMappings">列映射配置（属性名 -> 列标题）</param>
        /// <param name="filePath">导出文件路径</param>
        /// <param name="sheetName">工作表名称</param>
        public static void ExportToExcel<T>(List<T> data, Dictionary<string, string> columnMappings,
            string filePath, string sheetName = "Sheet1") where T : class
        {
            // 设置 EPPlus 许可证上下文为非商业用途
            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

            using (var package = new ExcelPackage())
            {
                var worksheet = package.Workbook.Worksheets.Add(sheetName);

                // 写入标题行
                int colIndex = 1;
                var propertyColumnMap = new Dictionary<string, int>();

                foreach (var mapping in columnMappings)
                {
                    worksheet.Cells[1, colIndex].Value = mapping.Value;
                    propertyColumnMap[mapping.Key] = colIndex;
                    colIndex++;
                }

                // 设置标题样式
                using (var range = worksheet.Cells[1, 1, 1, columnMappings.Count])
                {
                    range.Style.Font.Bold = true;
                    range.Style.Font.Size = 12;
                    range.Style.Fill.PatternType = ExcelFillStyle.Solid;
                    range.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(60, 150, 200)); // 蓝色背景
                    range.Style.Font.Color.SetColor(Color.White); // 白色字体
                    range.Style.Border.BorderAround(ExcelBorderStyle.Thin);
                    range.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                    range.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
                }

                // 写入数据行
                for (int i = 0; i < data.Count; i++)
                {
                    var item = data[i];
                    int rowIndex = i + 2; // 数据从第二行开始

                    foreach (var mapping in columnMappings)
                    {
                        var property = typeof(T).GetProperty(mapping.Key);
                        if (property != null)
                        {
                            int columnIndex = propertyColumnMap[mapping.Key];
                            var value = property.GetValue(item);

                            // 处理不同类型的值
                            if (value is DateTime dateTime)
                            {
                                worksheet.Cells[rowIndex, columnIndex].Value = dateTime;
                                worksheet.Cells[rowIndex, columnIndex].Style.Numberformat.Format = "yyyy-mm-dd hh:mm:ss";
                            }
                            else if (value is DateTimeOffset dateTimeOffset)
                            {
                                worksheet.Cells[rowIndex, columnIndex].Value = dateTimeOffset.DateTime;
                                worksheet.Cells[rowIndex, columnIndex].Style.Numberformat.Format = "yyyy-mm-dd hh:mm:ss";
                            }
                            else if (value is bool boolValue)
                            {
                                worksheet.Cells[rowIndex, columnIndex].Value = boolValue ? "是" : "否";
                            }
                            else if (value is null)
                            {
                                worksheet.Cells[rowIndex, columnIndex].Value = "";
                            }
                            else
                            {
                                worksheet.Cells[rowIndex, columnIndex].Value = value.ToString();
                            }

                            // 添加边框
                            worksheet.Cells[rowIndex, columnIndex].Style.Border.BorderAround(ExcelBorderStyle.Thin);
                            worksheet.Cells[rowIndex, columnIndex].Style.VerticalAlignment = ExcelVerticalAlignment.Center;
                        }
                    }

                    // 交替行颜色
                    if (i % 2 == 0)
                    {
                        using (var range = worksheet.Cells[rowIndex, 1, rowIndex, columnMappings.Count])
                        {
                            range.Style.Fill.PatternType = ExcelFillStyle.Solid;
                            range.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(240, 240, 240)); // 浅灰色背景
                        }
                    }
                }

                // 自动调整列宽
                worksheet.Cells.AutoFitColumns();

                // 设置合理的列宽范围
                for (int col = 1; col <= columnMappings.Count; col++)
                {
                    var column = worksheet.Column(col);
                    if (column.Width < 10)
                    {
                        column.Width = 10;
                    }
                    if (column.Width > 50)
                    {
                        column.Width = 50;
                    }
                }

                // 冻结首行
                worksheet.View.FreezePanes(2, 1);

                // 保存文件
                var file = new FileInfo(filePath);
                package.SaveAs(file);
            }
        }

    }
}
